package com.group1.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.group1.realtime.app.BaseAppV1;
import com.group1.realtime.bean.ExamScoreLevelBean;
import com.group1.realtime.common.Constant;
import com.group1.realtime.util.AtguiguUtil;
import com.group1.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

public class Dws_ExamScoreLevel extends BaseAppV1 {

    public static void main(String[] args) {
        new Dws_ExamScoreLevel().init(
                3052,
                2,
                "Dws_ExamScoreLevel",
                Constant.TOPIC_DWD_EXAM_USER_ATTEND_EXAM
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {

        SingleOutputStreamOperator<ExamScoreLevelBean> examScoreLevelStream = processStream(stream);
        //examScoreLevelStream.print();
        SingleOutputStreamOperator<ExamScoreLevelBean> aggregatedStream = windowAndAgg(examScoreLevelStream);
        aggregatedStream.print();
        // 3. 把结果写入到clickhouse中
        writeToClickHouse(aggregatedStream);

    }

    private void writeToClickHouse(SingleOutputStreamOperator<ExamScoreLevelBean> aggregatedStream) {
        aggregatedStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_exam_score_level_window", ExamScoreLevelBean.class));
    }


    private SingleOutputStreamOperator<ExamScoreLevelBean> windowAndAgg(SingleOutputStreamOperator<ExamScoreLevelBean> examScoreLevelStream) {

        return examScoreLevelStream.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        .<ExamScoreLevelBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((bean, ts) -> bean.getTs())
                        .withIdleness(Duration.ofSeconds(5))
        )
                .keyBy(bean -> bean.getPaperId() + "_" + bean.getScoreLevel())
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .sideOutputLateData(new OutputTag<ExamScoreLevelBean>("late") {
                })
                .reduce(
                        new ReduceFunction<ExamScoreLevelBean>() {
                            @Override
                            public ExamScoreLevelBean reduce(ExamScoreLevelBean value1, ExamScoreLevelBean value2) throws Exception {
                                value1.setLevelCt(value1.getLevelCt() + value2.getLevelCt());
                                return value1;
                            }
                        },
                        new ProcessWindowFunction<ExamScoreLevelBean, ExamScoreLevelBean, String, TimeWindow>() {
                            @Override
                            public void process(String key, Context ctx, Iterable<ExamScoreLevelBean> elements, Collector<ExamScoreLevelBean> out) throws Exception {
                                ExamScoreLevelBean bean = elements.iterator().next();
                                bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));

                                bean.setTs(ctx.currentProcessingTime());  // 把ts更新为聚合时间
                                out.collect(bean);
                            }
                        }
                );
    }

    private SingleOutputStreamOperator<ExamScoreLevelBean> processStream(DataStreamSource<String> stream) {

        return stream.map(new MapFunction<String, ExamScoreLevelBean>() {
            @Override
            public ExamScoreLevelBean map(String value) throws Exception {

                JSONObject obj = JSON.parseObject(value);
                double score = Double.parseDouble(obj.getString("score"));
                String paperId = obj.getString("paper_id");
                Long ts = obj.getLong("ts")*1000;
                if (score<60){
                    return new ExamScoreLevelBean("","",paperId,"不及格", 1L, ts);
                }else if (score>=60 && score<=75){
                    return new ExamScoreLevelBean("","",paperId,"及格", 1L, ts);
                }else if (score>75 && score<=85){
                    return new ExamScoreLevelBean("","",paperId,"良好", 1L, ts);
                }else {
                    return new ExamScoreLevelBean("","",paperId,"优秀", 1L, ts);
                }
            }
        });
    }
}
